import tkinter as tk
import requests
import wget
import os
import random
import json
import ftplib
import decimal

temp = os.getenv('TEMP')
home = os.getenv('HOMEPATH')
drive = os.getenv('HOMEDRIVE')
version = "3.0"

if decimal.Decimal(requests.get('http://110.42.191.105/api/update.txt').text) > decimal.Decimal(version):
    with open('error.txt', 'w') as c:
        c.write('您的版本已过时，请联系芦苇(1058115313)或去Gitee自行下载最新版本')
    os.system('start error.txt')
    os._exit(0)


def error(r):
    open('error.txt', 'w').write(f'下载{r}失败请检查个人网络或联系芦苇')
    os.system('start error.txt')


tunnel = "".join(random.sample('zyxwvutsrqponmlkjihgfedcbaZYXWVUTSRQPONMLKJIHGFEDCBA1234567890', 10))  # 随机生成隧道名

if not os.path.exists(f'{temp}/ico.ico'):
    try:
        wget.download('http://110.42.191.105/api/ico.ico', temp)
    except Exception:
        error('ico.ico')

if not os.path.exists(f'{temp}/frpc.exe'):
    try:
        with open(f'{temp}\info.txt', 'w') as c:
            c.write('JRFrp第一次启动(或清理系统后)需初始化请等待0~60秒(初始化时间取决于您的网速)\n60秒后若仍无窗口出现或出现Error报错，请检查您个人网络或联系芦苇')
        os.system('start %temp%/info.txt')
        wget.download('http://110.42.191.105/LWFrp/frpc.exe', temp)
    except Exception:
        error('frpc.exe')

api = '芦苇今日的随机诗句借接口次数已经用完，给可怜的芦苇打钱吧球球了QAQ'
try:
    api = json.loads(json.dumps(requests.get('https://v2.alapi.cn/api/hitokoto?token=PI4EVvFd1GHxQ4GV&type=i').json()))[
        "data"]["hitokoto"]
    print(api)
except Exception:
    if not '高级套餐' in requests.get('https://v2.alapi.cn/api/hitokoto?token=PI4EVvFd1GHxQ4GV&type=i').text:
        open('error.txt', 'w').write('从api获取诗句失败，如窗口仍然能打开，请继续使用，明日会自动恢复正常。如窗口不能打开或明日仍不能恢复正常，请检查个人网络或联系芦苇')
        os.system('start error.txt')

if not os.path.exists(f'{temp}/JRfrp.gif'):
    wget.download('http://110.42.191.105/api/JRfrp.gif', temp)

window = tk.Tk()  # 实例化Tk
window.title(f'JRFrp | {api}| MadeByLW')  # 给屎盆镶上金边
window.geometry("550x450")  # 设置窗口的大小
window.iconbitmap(f'{temp}/ico.ico')  # 注入灵魂
window.resizable(1, 0)
window.attributes("-topmost", 1)

info_serverip_1 = tk.Label(window,text='请输入①号服务器IP：')
info_serverip_1.grid(row=1, column=1, sticky=tk.W)
get_serverip_1 = tk.Entry(window)
get_serverip_1.grid(row=1, column=2)

info_serverip_2 = tk.Label(window,text='请输入②号服务器IP：')
info_serverip_2.grid(row=2, column=1, sticky=tk.W)
get_serverip_2 = tk.Entry(window)
get_serverip_2.grid(row=2, column=2)


info_local_port = tk.Label(window, text='请输入您的内网端口(默认25565)：')  # local port
info_local_port.grid(row=3, column=1, sticky=tk.W)
get_local_port = tk.Entry(window)
get_local_port.grid(row=3, column=2)

info_remote_port = tk.Label(window, text='请输入您的外网端口(默认25565)：')  # remote port
info_remote_port.grid(row=4, column=1, sticky=tk.W)
get_remote_port = tk.Entry(window)
get_remote_port.grid(row=4, column=2)

info_cp = tk.Label(window, text='请选择您的传输协议(默认tcp)：')  # cp
info_cp.grid(row=5, column=1, sticky=tk.W)
get_cp = tk.StringVar()
tk.Radiobutton(window, variable=get_cp, text='tcp', value='tcp').grid(row=6, column=1, sticky=tk.W)
tk.Radiobutton(window, variable=get_cp, text='udp', value='udp').grid(row=6, column=2, sticky=tk.W)

img_gif = tk.PhotoImage(file=f'{temp}/JRfrp.gif')
label_img = tk.Label(window, image=img_gif)
label_img.place(y=140,x=50)


def Confirm():
    def CheckIP(server_ip):
        visit_IP = os.popen('ping %s' % server_ip)
        # 读取结果
        result = visit_IP.read()
        # 关闭os.popen()
        visit_IP.close()
        # 判断IP是否在线
        if 'TTL' in result:
            if len(result) == 0:
                with open('error.txt', 'w') as c:
                    c.write('不可输入空数据')
            with open('JRFrp.ini', 'w') as c:
                c.write(
                    f'[common]\nserver_addr = {server_ip}\nserver_port = 7000\n\n[{tunnel}]\ntype = {cp}\nlocal_ip = 127.0.0.1\nlocal_port = {local_port}\nremote_port = {remote_port}')  # 写入数据至配置文件
            os.system('start %temp%/frpc -c JRFrp.ini')
        else:
            with open('error.txt', 'w') as inf:
                inf.write('您输入的服务器IP地址无效，请检查个人网络或查看IP是否存在')
            os.system('start error.txt')
            window.quit()

    local_port = get_local_port.get()  # 得到文本输入框的值
    if len(local_port) == 0 or local_port.isdigit() == False:
        local_port = '25565'
    print(local_port)

    remote_port = get_remote_port.get()
    if len(remote_port) == 0 or remote_port.isdigit() == False:
        remote_port = '25565'
    print(remote_port)

    cp = get_cp.get()
    if cp != 'tcp' or 'udp':
        cp = 'tcp'
    print(cp)

    serverip_1 = get_serverip_1.get()
    print(serverip_1)
    CheckIP(serverip_1)
    serverip_2 = get_serverip_2.get()
    print(serverip_2)
    CheckIP(serverip_2)
    window.quit()


def title():
    api = '芦苇今日的随机诗句借接口次数已经用完，给可怜的芦苇打钱吧球球了QAQ'
    try:
        api = json.loads(json.dumps(requests.get('https://v2.alapi.cn/api/hitokoto?token=PI4EVvFd1GHxQ4GV&type=i').json()))["data"]["hitokoto"]
        print(api)
    except Exception:
        if '太多请求了' in requests.get('https://v2.alapi.cn/api/hitokoto?token=PI4EVvFd1GHxQ4GV&type=i').text:
            api = '刷新太快了'
        if not '高级套餐' in requests.get('https://v2.alapi.cn/api/hitokoto?token=PI4EVvFd1GHxQ4GV&type=i').text:
            open('error.txt', 'w').write('从api获取诗句失败，可能有如下原因：①您刷新太快了 ②个人网络原因 ③今日芦苇api次数已过，可以等待到明日即可恢复正常')
            os.system('start error.txt')
    window.quit()
    window.title(f'JRFrp | {api}| MadeByLW')
    window.mainloop()

tk.Button(window, text="确定", width=15, height=2, command=Confirm).place(x=420, y=390)
tk.Button(window, text="刷新标题", width=15, height=2, command=title).place(x=300, y=390)
window.mainloop()  # 显示窗口
